package com.lun.medium;

import java.util.LinkedList;

public class SimplifyPath {

	// 方法一：我写的
	public String simplifyPath(String path) {
		LinkedList<String> dirs = new LinkedList<>();
		for (int p1 = 0, p2 = 1; p2 <= path.length(); p2++) {

			if (p2 == path.length() || path.charAt(p2) == '/') {
				String dir = path.substring(p1 + 1, p2);
				p1 = p2;

				if (dir.equals("") || dir.equals("."))
					continue;

				if (dir.equals("..")) {
					if (!dirs.isEmpty())
						dirs.removeLast();
				} else {
					dirs.add(dir);
				}
			}
		}

		StringBuilder sb = new StringBuilder();
		dirs.stream().forEach(dir -> sb.append("/").append(dir));
		return sb.length() == 0 ? "/" : sb.toString();
	}

	// 方法二：别人写的
	public String simplifyPath2(String path) {
		LinkedList<String> list = new LinkedList<>();
		for (String cur : path.split("/")) {
			if (cur.equals("..")) {
				if (!list.isEmpty())
					list.removeLast();
			} else if (cur.length() > 0 && !cur.equals("."))
				list.add(cur);
		}
		return "/" + String.join("/", list);
	}

}
